﻿using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using System;
using System.Threading;
using System.IO.IsolatedStorage;
using System.Device.Location;
using System.Collections.Generic;
using System.Device;
using System.Net;
using System.Text;
using System.IO;

namespace MapLocation
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;
        GeoCoordinateWatcher mywatch;
      
        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {

            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        Thread Shell;
        int Count = 0;
        protected override void OnInvoke(ScheduledTask task)
        {
            string message = "";

            {
                message = "Initialised";
            }

            DateTime timeStamp = DateTime.Now;
            string timeStampString = timeStamp.ToShortDateString() + " " + timeStamp.ToShortTimeString() + " ";

            GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();

            watcher.PositionChanged += (s, e) =>
                {
                    ShellToast toast = new ShellToast();
                    toast.Title = "Location Tracker";
                    toast.Content = e.Position.Location.Longitude.ToString();
                    toast.Show();
                };
            watcher.Start();

            
            string positionString = watcher.Position.Location.ToString() + System.Environment.NewLine;

            //if (Microsoft.Phone.Info.DeviceStatus.DeviceName == "XDeviceEmulator")
            {
                // GeoCoordinateWatcher.Position doesn't contian meaningful data in the emulator, so fake it
               // positionString = "In the emulator" + System.Environment.NewLine;
            }




            

//#if DEBUG_AGENT
           // ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
//#endif
            NotifyComplete();
        }
        private void WatcherPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            ShellToast toast = new ShellToast();

            toast.Title = "Running";
            toast.Content = e.Position.Location.Longitude+"---" + e.Position.Location.Latitude;
            toast.Show();
        }
        private void WatcherStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            ShellToast toast = new ShellToast();

            toast.Title = "Running";
            toast.Content = ""+e.Status;
            toast.Show();

            _status = e.Status;
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                case GeoPositionStatus.NoData:
                case GeoPositionStatus.Ready:
                    _watcherLock.Set();
                    break;
                case GeoPositionStatus.Initializing:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        private readonly GeoCoordinateWatcher _watcher = new GeoCoordinateWatcher();
        private readonly AutoResetEvent _watcherLock = new AutoResetEvent(false);
        private GeoPositionStatus _status;
    }
}